package com.chainyoung.component_tmmarket.ui;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chainyoung.common.adpter.BaseFragmentAdapter;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.bean.UserInfo;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.http.websocket.WebSoketUtils;
import com.chainyoung.common.http.websocket.WsManager;
import com.chainyoung.common.http.websocket.WsStatus;
import com.chainyoung.common.utils.CommonUtil;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.TablayoutUtils;
import com.chainyoung.component_tmmarket.R;
import com.chainyoung.component_tmmarket.R2;
import com.chainyoung.component_tmmarket.bean.MarketList;
import com.chainyoung.component_tmmarket.di.DaggerTradeMarketComponent;
import com.chainyoung.component_tmmarket.di.TradeMarketModule;
import com.chainyoung.component_tmmarket.mvp.contract.MarketMainContract;
import com.chainyoung.component_tmmarket.mvp.presenter.MarketMainPresenter;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;
import com.flyco.tablayout.SlidingTabLayout;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import q.rorbin.badgeview.QBadgeView;

import static android.support.design.widget.TabLayout.MODE_FIXED;



public class MarketMainFragment extends BaseFragment<MarketMainPresenter> implements MarketMainContract.View {


    @BindView(R2.id.tab_layout)
    SlidingTabLayout tabLayout;
    @BindView(R2.id.view_pager)
    ViewPager viewPager;
    @BindView(R2.id.rl_empty)
    RelativeLayout rlEmpty;


    private List<Fragment> fragmentList = new ArrayList<>();

    public WsManager wsManager;

    private QBadgeView badgeView;

    private MarketList mData;


    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerTradeMarketComponent.
                builder().
                appComponent(appComponent)
                .tradeMarketModule(new TradeMarketModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initData() {

    }


    @Override
    protected void initUi() {
        super.initUi();
        //showAndSetBarLeftText(getString(R.string.main_page));
        setCurrentTitle(R.string.market);
        showAndSetBarRightIcon(R.mipmap.ic_msg);
        showAndSetBarRightLeftIcon(R.mipmap.ic_search);
        initMsgNum();
        wsManager = WebSoketUtils.getWsManager();

    }


    private void initMsgNum() {
        int num = 0;
        if (CommonUtil.getUserInfo() != null) {
            num = CommonUtil.getUserInfo().getUnread_msg_num();
        }
        if (badgeView == null) {
            badgeView = new QBadgeView(mContext);
            badgeView.setBadgeBackgroundColor(ContextCompat.getColor(mContext, R.color._F95A54));
            badgeView.setBadgeTextColor(ContextCompat.getColor(mContext, R.color.white));
            badgeView.setBadgeTextSize(9, true);
            badgeView.bindTarget(mBarRightImageView).setBadgeGravity(Gravity.TOP | Gravity.END).
                    setGravityOffset(4, 3, true).
                    setBadgeNumber(num);
        } else {
            badgeView.setBadgeNumber(num);
        }
    }


    @Override
    public void onRightLeftImgClicked(View v) {
        super.onRightLeftImgClicked(v);
//        RouterUtils.getInstance()
//                .build(RouterConstants.PATH_MAIN_ACTIVITY)
//                .navigation();
        launch(SearchMarketActivity.class);
    }


    @Override
    public void onRightImgClicked(View v) {
        super.onRightImgClicked(v);
        RouterUtils.getInstance()
                .build(RouterConstants.PATH_MESSAGE_CENTER)
                .navigation();

    }

    @OnClick(R2.id.btn_retry)
    void refreshMarket() {
        mData = null;
        mPresenter.getMarketCurrencys();
    }


    @Override
    protected void onFirstUserVisible() {
        mPresenter.getMarketCurrencys();
    }

    @Override
    public void onUserInvisible() {
        super.onUserInvisible();
        wsManager.stopConnect();
    }

    @Override
    public void onUserVisible() {
        super.onUserVisible();
        if (mData == null) {
            mPresenter.getMarketCurrencys();
        }
        if (wsManager.getCurrentStatus() != WsStatus.CONNECTED && mData != null) {
            wsManager.startConnect();
        }
        getUserInfo();


    }

//    @OnClick(R2.id.et_search)
//    void onSearch() {
//        //跳转搜索页面
//        launch(SearchMarketActivity.class);
//    }
//

    @Override
    protected int getLayoutId() {
        return R.layout.tmmarket_fragment_trade_market;
    }


    //----------------------------------------------网络请求----------------------------------------

    private void getUserInfo() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        mPresenter.getUserInfo(map);
    }


    @Override
    public void showMarketCurrencys(MarketList data) {
        mData = data;
        rlEmpty.setVisibility(View.GONE);
        final List<String> titles = new ArrayList<>();
        titles.addAll(data.getRegion_list());
        for (int i = 0; i < titles.size(); i++) {
            fragmentList.add(MarketListFragment.newInstance(titles.get(i)));
        }
//        for (int i=0;i<fragmentList.size();i++){
//            ((MarketListFragment)fragmentList.get(i)).setCurrencyName(titles.get(i));
//        }

        viewPager.setAdapter(new BaseFragmentAdapter(getChildFragmentManager(), fragmentList, titles));
        tabLayout.setViewPager(viewPager);
        viewPager.setOffscreenPageLimit(titles.size());
        viewPager.setCurrentItem(0, false);
        wsManager.startConnect();
    }

    @Override
    public void onGetMarketCurrencysFailed() {
        rlEmpty.setVisibility(View.VISIBLE);
    }

    @Override
    public void onGetUserInfoSuccess(UserInfo userInfo) {
        UserInfo data = CommonUtil.getUserInfo();
        userInfo.setIs_setpaypassword(userInfo.getIs_setpaypassword());
        userInfo.setToken(userInfo.getToken());
        userInfo.setH5_chat_url(userInfo.getH5_chat_url());
        userInfo.setChatId(data.getChatId());
        CommonUtil.setUserInfo(userInfo);
        initMsgNum();
    }


    //----------------------------------------------event------------------------------------------

    @Subscriber
    void clearMsgNum(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.CLEAR_MSG) {
            badgeView.setBadgeNumber(0);
        }
    }

    @Subscriber
    void updateMsgNum(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.MSG_NUM) {
            HashMap<String, Integer> map = (HashMap<String, Integer>) event.getData();
            int num = 0;
            for (Integer integer : map.values()) {
                num += integer;
            }
            badgeView.setBadgeNumber(num);
        }
    }


}
